layui.define(['table', 'form', 'upload', 'admin'], function (exports) {
    var $ = layui.$
        , table = layui.table
        , form = layui.form
        , upload = layui.upload
        , admin = layui.admin;

    //商品列表
    table.render({
        elem: '#LAY-livestore-manage'
        , url: '/admin/live_store/getlist'
        , cols: [[
            {field: 'id', width: 70, title: 'ID', sort: true, fixed: 'left'}
            , {
                field: '', width: 100, title: '商品类型', templet: function (d) {
                    switch (d.type) {
                        case 1:
                            return '虚拟';
                        case 2:
                            return '实物';
                    }
                    return '';
                }
            }
            , {field: 'title', minWidth: 200, title: '商品名称'}
            , {field: 'content', width: 200, title: '商品介绍'}
            , {
                field: '', title: '商品图片', width: 100, templet: function (d) {
                    if (d.thumb) {
                        return '<img style="display: inline-block; height: 100%;" src= "' + d.thumb + '" layadmin-event="photosPreview" value="' + d.thumb + '">'
                    } else {
                        return "暂未上传";
                    }
                }
            }
            // , {
            //     field: '', title: '商品期限', width: 100, templet: function (d) {
            //         if (d.limit == 0) {
            //             return '永久';
            //         } else if (d.limit > 0) {
            //             return d.limit + '天';
            //         }
            //         return '';
            //     }
            // }
            , {field: 'diamond', title: '宝石价格', width: 100}
            , {field: 'gold', title: '钻石价格', width: 100}
            // , {
            //     field: '', title: '贵族折扣', width: 100, templet: function (d) {
            //         return d.vip_discount == 1 ? '是' : '否';
            //     }
            // }
            , {field: 'created_at', title: '添加时间', width: 180}
            , {
                field: '', title: '状态', width: 100, templet: function (d) {
                    return d.status == 1 ? '<span style="color: #009688">上架中</span>' : '<span style="color: #FF5722">已下架</span>';
                }
            }
            , {
                field: '', title: '操作人', width: 110, templet: function (d) {
                    return d.admin ? d.admin.name : '';
                }
            }
            , {title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-livestore-operation'}
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });

    //监听工具条
    table.on('tool(LAY-livestore-manage)', function (obj) {
        if (obj.event === 'setstatus') {
            var status = obj.data.status == 0 ? 1 : 0;
            var confirm_txt = status == 1 ? '确定要上架该改商品吗?' : '确定要下架该改商品吗?';
            layer.confirm(confirm_txt, function (index) {
                admin.req({
                    url: '/admin/live_store/set_status'
                    , data: {"id": obj.data.id,status:status}
                    , success(res) {
                        if (res.code == 0) {
                            table.reload("LAY-livestore-manage");
                            layer.msg(res.msg, {icon: 1});
                        }
                    }
                });
            });
        } else if (obj.event === 'edit') {
            var index = layer.open({
                type: 2
                , title: '编辑'
                , content: '/admin/live_store/edit?id=' + obj.data.id
                , maxmin: true
                , area: ['650px', '350px']
            });
            layer.full(index);
        }
    });


    // 商品添加
    form.on("submit(livestore-add)", function (obj) {
        layer.load();
        //提交
        admin.req({
            url: "/admin/live_store/add",
            data: obj.field,
            success: function (res) {
                layer.closeAll("loading");
                if (res.code == 0) {
                    layer.msg(res.msg, {icon: 1, time: 2000}, function () {
                        window.location.reload()
                    });
                }
            },
            complete: function () {
                layer.closeAll("loading");
            },
        });
        return false;
    });


    //监听工具条
    table.on('tool(LAY-order-manage)', function (obj) {
        if (obj.event === 'operation') {
            var index = layer.open({
                type: 2
                , title: '发货'
                , content: '/admin/shop/order_dev?id=' + obj.data.id
                , maxmin: true
                , area: ['500px', '400px']
            });
            layer.full(index);
        }
    });


    //查看照片
    admin.events.photosPreview = function (othis) {
        let urls = othis.attr("value");
        let urlarr = new Array();
        $.each(urls.split(","), function (i, val) {
            urlarr.push({"src": val});
        });
        layer.photos({
            photos: {
                "title": "查看照片" //相册标题
                , "data": urlarr
            }
            , shade: 0.01
            , closeBtn: 1
            , anim: 5
        });
    };

    //上传图片
    upload.render({
        url: '/admin/index/noOperation'
        , elem: '.LAY_iconImgUpload'
        , auto: true
        , choose: function (obj) {
            // 图片地址表单id
            var imginput_obj_id = this.idObjName;

            layer.load();
            var choosefile;
            obj.preview(function (index, file, result) {
                choosefile = file;
            });
            admin.req({
                url: '/admin/activity/signForCos'
                , success: function (res) {
                    if (res.code == 0) {
                        var cos = new COS({
                            getAuthorization: function (options, callback) {
                                var credentials = res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    ExpiredTime: res.data.expiredTime
                                });
                            }
                        });
                        cos.putObject({
                            Bucket: res.data.bucket,
                            Region: res.data.region,
                            Key: 'images/' + res.data.filename + choosefile.name,
                            Body: choosefile,
                        }, function (err, data) {
                            layer.closeAll('loading');
                            if (err) {
                                console.log(err);
                                layer.msg("上传失败", {icon: 5});
                            } else {
                                if (data.statusCode == 200) {
                                    $('#' + imginput_obj_id).val("https://" + data.Location);
                                } else {
                                    layer.msg("图片上传失败", {icon: 5});
                                }
                            }
                        });
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            })
        }
    });

    //查看图标
    admin.events.coverImgPreview = function (othis) {
        var pic_obj_id = othis.data('idname');
        var src = $('#' + pic_obj_id).val();
        layer.photos({
            photos: {
                "title": "查看图标" //相册标题
                , "data": [{
                    "src": src //原图地址
                }]
            }
            , shade: 0.01
            , closeBtn: 1
            , anim: 5
        });
    };


    exports('live_store', {})
});

function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d]/g, "");
    obj.value = obj.value.replace(/^\./g, "");
}


function inputNum(obj){
    obj.value = obj.value.replace(/[^\d.]/g,"");
    obj.value = obj.value.replace(/^\./g,"");
    obj.value = obj.value.replace(/\.{2,}/g,".");
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');

    if(obj.value.indexOf(".")> 0  && obj.value.indexOf("0")>2){
        obj.value= parseFloat(obj.value);
    }
    if(obj.value.indexOf(".")> 0  && obj.value.lastIndexOf("0")>2){
        obj.value= parseFloat(obj.value);
    }
    if (obj.value.indexOf(".") <= 0 && obj.value != "") {
        obj.value = parseFloat(obj.value);
    }
}